package obecto.task
{
	import flash.events.EventDispatcher;
	
	import obecto.event.TaskEvent;
	import obecto.event.TaskEventKind;
	
	[Event(name="start", type="obecto.event.TaskEvent")]
	[Event(name="complete", type="obecto.event.TaskEvent")]
	
	[DefaultProperty("methodArguments")]
	public class ExecuteMethodTask extends EventDispatcher implements ITask
	{
		[Bindable] public var method : Function;
		[Bindable] public var methodArguments : Array;
		[Bindable] public var methodScope : *; // TODO: check if we need method scope in AS3
		
		private var _running : Boolean = false;
		public function get running() : Boolean
		{
			return _running;
		}
		
		public static function create(method : Function, methodArguments : Array, methodScope : * = null) : ExecuteMethodTask
		{
			var result : ExecuteMethodTask = new ExecuteMethodTask();
			result.method = method;
			result.methodArguments = methodArguments;
			result.methodScope = methodScope;
			return result;
		}
		
		public function start() : void
		{
			_running = true;
			dispatchEvent(new TaskEvent(TaskEvent.START));
			
			method.apply(methodScope, methodArguments);
			
			_running = false;
			dispatchEvent(new TaskEvent(TaskEvent.COMPLETE, TaskEventKind.END));
		}
	}
}